package com.shangguan.spring.config;

import com.shangguan.spring.realm.UserRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: ShiroConfiguration
 * @Description:
 * @Author: 一尘
 * @Date: 2020 年 05 月 19 14:45
 * @Version 1.0
 */
@Configuration
public class ShiroConfiguration {

    //shiro的核心配置
    @Bean("userRealm")
    public UserRealm userRealm(HashedCredentialsMatcher  hashedCredentialsMatcher){
        UserRealm userRealm = new UserRealm();
            userRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return userRealm;
    }

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm")UserRealm userRealm){
               DefaultWebSecurityManager  securityManager = new DefaultWebSecurityManager();
                securityManager.setSessionManager(new DefaultWebSessionManager());
               securityManager.setRealm(userRealm);
               return securityManager;
    }

    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
        return  new LifecycleBeanPostProcessor();
    }

    @Bean
    public ShiroFilterFactoryBean  shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean  factoryBean = new ShiroFilterFactoryBean();
            factoryBean.setSecurityManager(defaultWebSecurityManager);
            Map<String,String> map = new HashMap<>();
                map.put("/login","anon");
                map.put("/static/**","anon");
                map.put("/index","anon");
                map.put("/swagger","anon");
            factoryBean.setFilterChainDefinitionMap(map);

            return factoryBean;
    }

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher  hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        hashedCredentialsMatcher.setHashIterations(1024);
        return hashedCredentialsMatcher;
    }
}
